# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from jms.dm.dm_warehousing_weight_type_sum_dt import jms_dm__dm_warehousing_weight_type_sum_dt
#doris表名
doris_table = "dm_warehousing_weight_type_sum_dt"
#label名
label = f"{doris_table}_{int(time())}"
#hive中表名
hive_table = "dm_warehousing_weight_type_sum_dt"
#hdfs文件路径
hdfs_path ="hdfs://{{var.value.hadoop_namespace}}/dw/hive/jms_dm.db/external/"
timeout = timedelta(hours=2).seconds
#判断当天分区是否存在
file_path = f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | cst_ds }}}}/*"'
partition_lists = []
path_lists = []
for i in range(0, 1):
    if i == 0:
        partition_lists.append("p{{ execution_date | cst_ds_nodash }}")
        path_lists.append(file_path)
    else:
        partition_lists.append("p{{ execution_date | date_add(-" + str(i) + ") | cst_ds_nodash }}")
        path_lists.append(f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | date_add(-{i}) | cst_ds }}}}/*"')

partition_str = ",".join(partition_lists)
path_str = ",".join(path_lists[::-1])
doris_jms_dm__dm_warehousing_weight_type_sum_dt = RichSqlSensor(
    task_id='doris_jms_dm__dm_warehousing_weight_type_sum_dt',
    pool='broker_load_pool',
    email=['matthew.xiong@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    task_concurrency=1,
    conn_id='doris',
    pre_sql=f"""
                 TRUNCATE TABLE jms_dm.{doris_table} PARTITION ({partition_str});
                 LOAD LABEL jms_dm.{label} (
                     DATA INFILE({path_str})
                     INTO TABLE {doris_table}
                     FORMAT AS 'PARQUET'(
                        network_code
                        , network_name
                        , agent_code
                        , agent_name
                        , city_id
                        , city_name
                        , province_id
                        , province_name
                        , zone_id
                        , zone_code
                        , zone_name
                        , zone_staff_code
                        , zone_staff_name
                        , area_code
                        , area_name
                        , area_staff_code
                        , area_staff_name
                        , weight_cnt
                        , manual_weight_cnt
                        , month_acc_weight_cnt
                        , month_acc_manual_weight_cnt
                        , month_acc_over_rate_cnt
                     )
                   columns from path as (dt)
                   set(
                        network_code                    =  network_code                 
                        , network_name                  =  network_name               
                        , agent_code                    =  agent_code                 
                        , agent_name                    =  agent_name                 
                        , city_id                       =  city_id                    
                        , city_name                     =  city_name                  
                        , province_id                   =  province_id                
                        , province_name                 =  province_name              
                        , zone_id                       =  zone_id                    
                        , zone_code                     =  zone_code                  
                        , zone_name                     =  zone_name                  
                        , zone_staff_code               =  zone_staff_code            
                        , zone_staff_name               =  zone_staff_name            
                        , area_code                     =  area_code                  
                        , area_name                     =  area_name                  
                        , area_staff_code               =  area_staff_code            
                        , area_staff_name               =  area_staff_name            
                        , weight_cnt                    =  weight_cnt                 
                        , manual_weight_cnt             =  manual_weight_cnt          
                        , month_acc_weight_cnt          =  month_acc_weight_cnt       
                        , month_acc_manual_weight_cnt   =  month_acc_manual_weight_cnt
                        , month_acc_over_rate_cnt       =  month_acc_over_rate_cnt
                        , dt                            =  dt
                   )
                 )
                 WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
                 PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

doris_jms_dm__dm_warehousing_weight_type_sum_dt << [jms_dm__dm_warehousing_weight_type_sum_dt]
        
        
        